﻿using AlibabaCloud.SDK.Dysmsapi20170525.Models;

namespace LF.Application.Helpers
{
   
    public class SmsHelper
    {
        
        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="phoneNumber">待发送手机号, 多个以逗号分隔</param>
        /// <param name="template">短信模板,模板类型(对应配置中的type)</param>
        /// <param name="param">模板中的变量对象</param>
        /// <returns></returns>
        public static async Task<string?> SendSms(string phoneNumber, Template template, object param)
        {
            var json = System.Text.Json.JsonSerializer.Serialize(param);
            if (!phoneNumber.IsValidPhoneNumber())
                return "手机号不正确";

            var config = LFConfig.Aliyun;
            var temp = config.Templates.FirstOrDefault(p => p.Template == template);
            if (temp == null)
                return "没有对应模板";

            var sendSmsRequest = new SendSmsRequest
            {
                PhoneNumbers = phoneNumber,
                SignName = config.SignName, // 短信签名
                TemplateCode = temp.Code, 
                TemplateParam = json, 
                //OutId = YitIdHelper.NextId().ToString()
            };
            try
            {
                var client = CreateClient();
                var sendSmsResponse = await client.SendSmsAsync(sendSmsRequest);
                if (sendSmsResponse.Body.Code == "OK" && sendSmsResponse.Body.Message == "OK")
                {
                    return "ok";
                }
                else
                {
                    var msg = sendSmsResponse.Body.Message;
                    Serilog.Log.Error(msg);
                    return msg;
                }
            }
            catch (Exception ex) {
                Serilog.Log.Error(ex, $"发送消息错误：模板{template} 手机号{phoneNumber} 内容{param}");
                return "error";
            }
            
        }


        private static AlibabaCloud.SDK.Dysmsapi20170525.Client CreateClient()
        {
            var cf = LFConfig.Aliyun;
            var config = new AlibabaCloud.OpenApiClient.Models.Config
            {
                AccessKeyId = cf.AccessKeyId,
                AccessKeySecret = cf.AccessKeySecret,
                Endpoint = "dysmsapi.aliyuncs.com"
            };
            return new AlibabaCloud.SDK.Dysmsapi20170525.Client(config);
        }
    }
}
